package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {

    //专门处理自定义异常
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionCustomHandler(CustomException ce){
        log.error(ce.getMessage());
        return R.error(ce.getMessage());
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            return R.error("输入的" + split[2] + "不允许有重复值");
        }
        return R.error("未知错误");
    }

    //其他数据库异常
    @ExceptionHandler(SQLException.class)
    public R<String> exceptionHandler(SQLException ex) {
        log.error(ex.getMessage());
        return R.error("错误:" + ex.getMessage());
    }
}
